package com.liunian.discovery;

import com.liunian.Constant;
import com.liunian.discovery.impl.NacosRegistry;
import com.liunian.discovery.impl.ZookeeperRegistry;
import com.liunian.exceptions.DiscoveryException;

public class RegistryConfig {

    // 定义连接的URL zookeeper://127.0.0.1:2181  redis://192.168.125：3306
    private final String connectString;

    public RegistryConfig(String connectString) {
        this.connectString = connectString;
    }

    /**
     * 可以使用简单工厂来完成
     * @return 具体的注册中心实例
     */
    public Registry getRegistry() {
        // 第一步：获取注册中心的类型（例如：zookeeper，redis等）
        String registryType = getRegistryType(connectString, true).toLowerCase().trim();
        if (registryType.equals("zookeeper")) {
            String host = getRegistryType(connectString, false);
            return new ZookeeperRegistry(host, Constant.Time_out);
        } else if (registryType.equals("nacos")) {
            String host = getRegistryType(connectString, false);
            return new NacosRegistry(host, Constant.Time_out);
        }
        throw new DiscoveryException("未发现合适的注册中心。");
    }

    private String getRegistryType(String connectString, boolean ifType) {
        String[] typeAndHost = connectString.split("://");
        if (typeAndHost.length != 2) {
            throw new RuntimeException("给定的注册中心连接URL不合法。");
        }
        if (ifType) {
            return typeAndHost[0];
        } else {
            return typeAndHost[1];
        }
    }
}
